package com.jida.tijian.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jida.tijian.domain.Users;
import com.jida.tijian.dto.ResponseObject;
import com.jida.tijian.service.UsersService;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jdk.internal.net.http.HttpRequestBuilderImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController//后端接口给前端穿的数据也是json对象
public class UserController {

    @Autowired
    UsersService usersService;
    /**
     * 定义处理登录请求的方法
     */

    @RequestMapping(value = "/login",method = {RequestMethod.POST})
    public ResponseObject<Users> login(@RequestBody Users users,HttpServletResponse response) { //Json对象转换为Java对象
        System.out.println("users:" + users.getUserId()+","+users.getPassword());


            //controller--service-->Mapper
        //1.根据手机号查询用户，看是否存在这个用户，2.根据密码，比对用户密码是否正确

        //Users u = users;
        //ResponseObject<Users> responseObject = new ResponseObject<>(200,u,"成功");
        ResponseObject<Users> responseObject = usersService.login(users);
        if (responseObject.getStatus() == 200) {
            try {
                Users user = responseObject.getData();
                Map<String, Object> map = new HashMap<>();
                map.put("currentUser", new ObjectMapper().writeValueAsString(user));

                JwtBuilder builder = Jwts.builder()
                        .setId(UUID.randomUUID().toString())
                        .setIssuedAt(new Date())
                        .signWith(SignatureAlgorithm.HS256, "123456-----")
                        .setExpiration(new Date(System.currentTimeMillis() + 1000 * 60 * 20))
                        .setClaims(map)
                        .setSubject(user.getUserId());

                String key = builder.compact();
                response.setHeader("token", key);
                System.out.println("返回数据给前端，token已生成");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return responseObject;

    }

    /**
     * 定义处理注册请求的方法
     */

    /**
     * 定义处理修改密码请求的方法
     */

    /**
     * 定义处理快捷登录请求的方法
     */
}

